<template>
  <div class="h-full flex flex-col">
    <div class="flex flex-between items-center p-2 mb-2 border-b">
      <a-input-search v-model:value="searchKey" class="w-64" placeholder="姓名/助记码/床位号" @search="getData" />
      <div v-if="levelCount.length > 0" class="flex border border-dashed border-gray-300 rounded-full px-12 py-1">
        <a-space :size="20">
          <div v-for="level in levelCount" :key="level" class="flex-center">
            <NurseLevelIcon :icon-code="level.iconCode" />
            <span class="font-bold ml-1"> {{ level.hzs || 0 }}人</span>
          </div>
        </a-space>
      </div>
      <div class="w-64 flex justify-end items-center">
        <BaseExport
          type="住院"
          name="新入区"
          code="000091"
          class="my-1"
          :search-params="{
            statuss: [0, 2],
            bqbh: store.areaCode,
            pyjm: searchKey,
            hiddenEmptyBed: true,
            lastDeptRegTimeStart: dayjs().format('YYYY-MM-DD'),
            lastDeptRegTimeEnd: dayjs().format('YYYY-MM-DD')
          }"
          >导出</BaseExport
        >
        <div class="absolute top-[-9999px] hidden">
          <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
          <a-button ref="printMeBeb" v-print="{ id: 'printMeBeb' }">打印</a-button>
          <PrintView id="printMe" :print-data="printData" />
          <PrintViewBeb id="printMeBeb" :print-data="printData" />
        </div>
      </div>
    </div>
    <BaseTable column-code="000091" :loading="loading" :scroll="{ x: 2200 }" :data-source="tableData" fill>
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'xh'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'status'">
          <a-tag color="blue">{{ ['在院', '已出院', '待出院', '待入区', '作废'][record.status] }}</a-tag>
        </template>
        <template v-if="column.dataIndex === 'brName'">
          <InPatientPopover
            v-model:open="record.openPopover"
            is-modify
            :patient-info="record"
            @change="getData"
            @click="record.openPopover = !record.openPopover"
          >
            <div class="cursor-pointer text-primary hover:underline">{{ record.brName }}</div>
          </InPatientPopover>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <BaseButton type="link" size="small" @click="onAction('换床', record)"> 换床 </BaseButton>
          <BaseButton type="link" size="small" @click="onAction('更换护理等级', record)"> 更换护理等级 </BaseButton>
          <a-dropdown>
            <BaseButton type="link" size="small" :icon="h(EllipsisOutlined)" />
            <template #overlay>
              <a-menu>
                <a-menu-item>
                  <BaseButton type="link" size="small" @click="onClickBook(record)"> 费用记账 </BaseButton>
                </a-menu-item>
                <a-menu-item v-if="record.inpDischarge">
                  <BaseButton type="link" size="small" @click="onDischarge(record)"> 通知出院 </BaseButton>
                </a-menu-item>
                <a-menu-item v-if="record.inpTransferZone">
                  <BaseButton type="link" size="small" @click="onAction('转区', record)"> 转区 </BaseButton>
                </a-menu-item>
                <a-menu-item>
                  <BaseButton type="link" size="small" @click="openReplace(record)"> 更换医护 </BaseButton>
                </a-menu-item>
                <a-menu-item>
                  <BaseButton type="link" size="small" @click="onPrint(record)"> 床卡 </BaseButton>
                </a-menu-item>
                <a-menu-item>
                  <BaseButton type="link" size="small" @click="onPrintWrist(record)"> 腕带 </BaseButton>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </template>
    </BaseTable>
    <OperateModal v-model:open="modalStatus.open" :data="currentBed" :type="modalStatus.type" @success="onSuccess" @close="currentBed = {}" />
    <EnterModal v-model:open="registrationOpen" :row-data="registrationRow" @success="onSuccess" />
    <ReplaceDoctor v-model:open="replaceModal" :data="currentBed" @success="onSuccess" />
    <!-- 催款单 -->
    <DemandModal
      v-model:open="depositModal"
      :patient-info="{ ...patientInfo, deJeCount: patientInfo.dpJe, settlementAmount: patientInfo.zyfy, wardName: patientInfo.wardName }"
      @success="getData"
    />
  </div>
</template>
<script setup>
import { reactive, ref, watchEffect, h, createVNode } from 'vue'
import { message } from 'ant-design-vue'
import { EllipsisOutlined } from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import InPatientPopover from '@/components/InPatientPopover'
import { post, get } from '@/utils/request'
import DemandModal from '@/views/in-registration/components/DemandModal.vue'
import { getSystemConfig } from '@/utils/systemConfig'
import useStore from '../../store'
import EnterModal from '../component/EnterModal'
import PrintView from '../component/PrintView.vue'
import PrintViewBeb from '../component/PrintViewBeb.vue'
import OperateModal from '../InArea/OperateModal.vue'
import ReplaceDoctor from '../InArea/ReplaceDoctor.vue'

const store = useStore()
const riskData = ref([])
const router = useRouter()
const modalStatus = reactive({ open: false, type: '' })
const registrationOpen = ref(false)
const replaceModal = ref(false)
const registrationRow = ref({})
const currentBed = ref({})
const searchKey = ref('')
const levelCount = ref([])
const depositModal = ref(false)
const patientInfo = ref({})
const printData = ref({})
const printMe = ref()
const printMeBeb = ref()

const { loading, tableData, getData } = useTable({
  url: '/inp/zydj/getInpRecordList',
  immediate: true,
  pagination: false,
  formatParams: () => {
    return {
      statuss: [0, 2],
      bqbh: store.areaCode,
      pyjm: searchKey.value,
      lastDeptRegTimeStart: dayjs().format('YYYY-MM-DD'),
      lastDeptRegTimeEnd: dayjs().format('YYYY-MM-DD'),
      hiddenEmptyBed: true
    }
  },
  onSuccess: () => {
    tableData.value.forEach((item) => (item.openPopover = false))
  }
})

const onSuccess = () => {
  getLevelCount()
  getData()
}

const getRiskData = async () => {
  const { data = [], code } = await post('/operation/opex/getDictCommonItemList', { dictCommonCode: 'DT00314', status: 1 })
  if (code === 0) {
    riskData.value = data
  }
}

const getLevelCount = async () => {
  const { code, data } = await get('/inp/zyhs/getPatientCountbyNursingGradeList?bqbh=' + store.areaCode)
  if (code === 0) {
    levelCount.value = data
  }
}
watchEffect(() => {
  getLevelCount()
})
const onAction = (type, row) => {
  currentBed.value = row
  modalStatus.type = type
  modalStatus.open = true
}
const openReplace = (row) => {
  currentBed.value = row
  replaceModal.value = true
}

//出院
const onDischarge = async (row) => {
  Modal.confirm({
    title: '提示',
    okText: '确定',
    centered: true,
    maskClosable: true,
    width: 560,
    cancelText: '取消',
    icon: createVNode(ExclamationCircleOutlined, { style: 'color:red' }),
    content: createVNode('div', { style: 'margin:24px 0;font-size:15px' }, '确定通知出院？'),
    onOk: async () => {
      const { code, msg } = await post('/inp/zyys/doNoticeOfDischarge', {
        inplsh: row.inplsh,
        advId: row.inpDischarge?.inpAdvId
      })
      if (code !== 0) return message.error(msg || '操作失败')
      message.success(msg || '通知出院成功')
      store.getStatusCount()
      onSuccess()
    }
  })
}

// 床卡打印
const onPrint = async (row) => {
  const { code, msg, data } = await post('/inp/Print/bedCardPrint', {
    inplsh: row.inplsh
  })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      printMeBeb.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}

// 腕带
const onPrintWrist = async (row) => {
  const { code, msg, data } = await post('/inp/Print/inpWristbandsPrint', {
    inplsh: row.inplsh
  })
  if (code !== 0) return message.error(msg)

  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      printMe.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}
//住院须知
const wardMemo = ref('')
const onQueryWardMemo = async () => {
  const { code, msg, data } = await post('/inp/zyhs/queryWardMemo', {
    wardId: store.areaCode
  })
  if (code !== 0) return message.error(msg)
  wardMemo.value = data
}

// 费用记账-跳转补记账
const onClickBook = (row) => {
  router.push({
    path: '/in-nurse/patient-management/billing',
    query: {
      inplsh: row.inplsh
    }
  })
}
onMounted(() => {
  getRiskData()
  onQueryWardMemo()
})
</script>
